<?php

class UloginModel extends CModel {

    public $identity;
    public $network;
    public $email;
    public $full_name;
    public $token;
    public $error_type;
    public $error_message;
    public $login;
    
    private $uloginAuthUrl = 'http://ulogin.ru/token.php?token=';

    public function rules() {
        return array(
            array('identity,network,token', 'required'),
            array('email', 'email'),
            array('identity,network,email', 'length', 'max'=>255),
            array('full_name', 'length', 'max'=>55),
        );
    }

    public function attributeLabels() {
        return array(
            'network'=>'Сервис',
            'identity'=>'Идентификатор сервиса',
            'email'=>'eMail',
            'full_name'=>'Имя',
        );
    }

    public function getAuthData() {
        $authData = json_decode(file_get_contents($this->uloginAuthUrl.$this->token.'&host='.$_SERVER['HTTP_HOST']),true);
        if(!empty($authData['error'])) Yii::app()->getController()->redirect(array('user/default/login'));
        $this->setAttributes($authData);
        $this->full_name = $authData['first_name'].' '.$authData['last_name'];
        $this->login = $authData['first_name'];
    }

    public function login() {
        $identity = new UloginUserIdentity();
        $identity->authenticate($this); 
        switch($identity->errorCode) {
            case UserIdentity::ERROR_NONE:
                Yii::app()->user->login($identity,3600*24*30);
                break;
            case UserIdentity::ERROR_ACCOUNT_BLOCKED:
                $this->addError('uloginErrors', 'Ваш аккаунт заблокирован до '.Yii::app()->dateFormatter->format("HH:mm dd MMMM yyyy года", $identity->unblockDate));
                break;
            case UserIdentity::ERROR_ACCOUNT_BANNED:
                $this->addError('uloginErrors', 'Ваш аккаунт заблокирован бессрочно');
                break;
            case UserIdentity::ERROR_USERNAME_INVALID:
                $this->addError('uloginErrors', 'Подобной комбинации пароля и логина нет');
                break;
            return !$this->hasErrors();
        }
        return false;
    }

    public function attributeNames() {
        return array(
            'identity', 'network', 'email', 'full_name', 
            'token', 'error_type', 'error_message'
        );
    }
}
